import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Image,
    FlatList,
    StatusBar,
    TextInput,
    ScrollView,
    Picker,
    DeviceEventEmitter
} from 'react-native';
import { base } from "../../../assets/style";
import LinearGradient from "react-native-linear-gradient";
import SegmentedControlTab from "react-native-segmented-control-tab";
import ImagePicker from 'react-native-image-picker';
import { getMime } from "../../../utils/utils";
import Toast from "react-native-easy-toast";
import Loading from "../../../components/loading";
import { API } from "../../../api";
import { i18n } from "../../../utils/locales/i18n";

// More info on all the options is below in the API Reference... just some common use cases shown here
const options = {
    title: '选择相片',
    // customButtons: [{ name: 'fb', title: 'Choose Photo from Disk' }],
    storageOptions: {
        skipBackup: true,
        path: 'images',
    },
};

type Props = {};
export default class Verify extends Component<Props> {
    static navigationOptions = ({ navigation }) => {
        return {
            title: i18n.t('ver_name'),
            headerStyle: {
            },
            headerTintColor: '#0f0f0f',
            headerBackTitle: null
        }
    };
    constructor() {
        super();
        this.state = {
            name: '',
            idNumber: '',
            selectedIndex: 0,
            idFrontPreview: '',
            idBackPreview: '',
            passPortPreview: '',
            modalVisible: false,
            currentToastInfo: '',

            passportNumber: '',
            passportName: '',

            fileIdFront: '',
            fileIdBack: '',
            filePass: ''
        }

    }
    changeTab(index) {
        this.setState({
            selectedIndex: index
        })
    }
    selectImage = async (type) => {
        // type 1 身正 2 身反 3 护照
        const imageRes = await this.showImagePicker()
        // data: "/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAA"
        // fileName: "IMG_0001.JPG"
        // fileSize: 6209998
        // height: 2848
        // isVertical: false
        // latitude: 38.0374445
        // longitude: -122.80317833333334
        // origURL: "assets-library://asset/asset.JPG?id=106E99A1-4F6A-45A2-B320-B0AD4A8E8473&ext=JPG"
        // timestamp: "2011-03-13T00:17:25Z"
        // uri: "file:///Users/ishi/Library/Developer/CoreSimulator/Devices/CFF33CAA-6A1B-4D2C-9542-B424C3DE3A42/data/Containers/Data/Application/A73DC928-F7EB-4824-9344-941071C3466A/Documents/images/DBAA19D3-E8D8-4071-8600-E90B7860671E.jpg"
        // width: 4288
        // this.state.formData = ;
        const file = {
            uri: imageRes.uri,
            type: getMime(imageRes.fileName),
            name: imageRes.fileName.toLowerCase(),
            size: imageRes.fileSize,
        };
        const baseImg = `data:${file.type};base64,${imageRes.data}`
        switch (type) {
            case 1:
                this.setState({
                    idFrontPreview: { uri: baseImg },
                    fileIdFront: file
                })
                break
            case 2:
                this.setState({
                    idBackPreview: { uri: baseImg },
                    fileIdBack: file
                })
                break
            case 3:
                this.setState({
                    passPortPreview: { uri: baseImg },
                    filePass: file
                })
                // formData.append('card_back', file);
                break
        }
        // console.log('formData', formData);
    }
    showImagePicker = () => {
        /**
         * The first arg is the options object for customization (it can also be null or omitted for default options),
         * The second arg is the callback which sends object: response (more info in the API Reference)
         */
        // console.log('Response = ', response);

        return new Promise((resolve, reject) => {
            ImagePicker.showImagePicker(options, (response) => {
                if (response.didCancel) {
                    console.log('You cancelled image picker');
                    resolve(response)
                } else if (response.error) {
                    console.log('ImagePicker Error: ', response.error);
                    reject(response)
                } else if (response.customButton) {
                    console.log('User tapped custom button: ', response.customButton);
                    resolve(response)
                } else {
                    // const source = { uri: response.uri };
                    resolve(response)
                    // You can also display the image using data:
                    // const source = { uri: 'data:image/jpeg;base64,' + response.data };

                    // this.setState({
                    //     avatarSource: source,
                    // });
                }
            });
        })
    }
    // 提交身份证验证
    submitIdKyc = async () => {
        if (!this.state.name || !this.state.idNumber) {
            this.refs.toast.show(i18n.t('plz_cpl'))
            return
        }
        if (!this.state.fileIdFront || !this.state.fileIdBack) {
            this.refs.toast.show(i18n.t('info22'))
            return
        }
        this.setState({
            modalVisible: true,
            currentToastInfo: i18n.t('loading')
        })
        const formData = new FormData()
        formData.append('id_name', this.state.name)
        formData.append('id_number', this.state.idNumber)
        formData.append('card_front', this.state.fileIdFront)
        formData.append('card_back', this.state.fileIdBack)
        const res = await API.uploadIdCard(formData)
        this.setState({
            modalVisible: false,
            currentToastInfo: ''
        })
        // code: 10000
        // data: ""
        // msg: "上传实名信息成功"
        // status: 200
        // console.log('formData', res);
        if (res.code === 10000) {
            this.refs.toast.show(res.msg || i18n.t('o_success'))
            setTimeout(() => {
                DeviceEventEmitter.emit('refresh_user_info');
                this.props.navigation.goBack()
            }, 0)
        } else {
            this.refs.toast.show(res.msg || i18n.t('o_defeat'))
        }
    }
    // 提交护照验证
    submitPassportKyc = async () => {
        if (!this.state.passportName || !this.state.passportNumber) {
            this.refs.toast.show(i18n.t('plz_cpl'))
            return
        }
        if (!this.state.filePass) {
            this.refs.toast.show(i18n.t('info22'))
            return
        }
        this.setState({
            modalVisible: true,
            currentToastInfo: i18n.t('loading')
        })
        const formData = new FormData()
        formData.append('id_name', this.state.passportName)
        formData.append('id_number', this.state.passportNumber)
        formData.append('passport', this.state.filePass)
        const res = await API.uploadPassport(formData)
        this.setState({
            modalVisible: false,
            currentToastInfo: ''
        })
        // code: 10000
        // data: ""
        // msg: "上传实名信息成功"
        // status: 200
        // console.log('formData', res);
        if (res.code === 10000) {
            this.refs.toast.show(res.msg || i18n.t('o_success'))
            setTimeout(() => {
                DeviceEventEmitter.emit('refresh_user_info');
                this.props.navigation.goBack()
            }, 0)
        } else {
            this.refs.toast.show(res.msg || i18n.t('o_defeat'))
        }
    }
    render() {
        return (
            <View style={[base.flex_1, base.bg_white]}>
                {/*toast*/}
                <Toast ref="toast" position='bottom' positionValue={200}/>
                { this.state.modalVisible ? (
                    <Loading
                        info={this.state.currentToastInfo}
                    />) : null }
                <View style={[{ height: 90, width: '100%' }, base.flex_col_center, base.bg_white]}>
                    <View style={{width: '50%'}}>
                        <SegmentedControlTab
                            values={[i18n.t('idc'), i18n.t('passp')]}
                            selectedIndex={this.state.selectedIndex}
                            tabStyle={{backgroundColor: '#fff', borderColor: '#ff7706' }}
                            activeTabStyle={{backgroundColor: '#ff7706'}}
                            tabTextStyle={{color: '#ff7706', fontSize: 18}}
                            activeTabTextStyle={{color: '#fff'}}
                            onTabPress={(index) => this.changeTab(index)}
                        />
                    </View>
                </View>
                <ScrollView style={[base.flex_1, { width: '100%' }]}>
                    { this.state.selectedIndex === 0 ? (
                        <View style={[{backgroundColor: '#fff', paddingBottom: 30}]}>
                            <View style={[base.bg_white, base.content_container]}>
                                <View style={{paddingBottom: 5, width: '100%'}}>
                                    <View style={[base.flex_row_start, { paddingVertical: 5 }]}>
                                        <Image style={{width: 15, height: 15, marginRight: 10}} resizeMode={'contain'} source={require('@images/mine/icon_real_name.png')}/>
                                        <View>
                                            <Text style={[base.color_orange, { fontSize: 16 }]}>{ i18n.t('rname') }</Text>
                                        </View>
                                    </View>
                                    <View style={{width: '100%'}}>
                                        <View style={[base.flex_row_between, { marginVertical: 5, height: 45, width: '100%', borderRadius: 5, borderWidth: 0.5, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>
                                            <TextInput
                                                style={[base.color_gray, {width: '100%'}]}
                                                value={this.state.name}
                                                onChangeText={(text) => this.setState({name: text})}
                                                placeholder={i18n.t('i242')}
                                            />
                                        </View>
                                    </View>
                                </View>
                                <View style={{paddingBottom: 5}}>
                                    <View style={[base.flex_row_start, { paddingVertical: 5 }]}>
                                        <Image style={{width: 15, height: 15, marginRight: 10}} resizeMode={'contain'} source={require('@images/mine/icon_real_name.png')}/>
                                        <View><Text style={[base.color_orange, { fontSize: 16 }]}>{ i18n.t('cnum') }</Text></View>
                                    </View>
                                    <View>
                                        <View style={[base.flex_row_between, { marginVertical: 5, height: 45, width: '100%', borderRadius: 5, borderWidth: 0.5, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>
                                            <TextInput
                                                style={[base.color_gray, {width: '100%'}]}
                                                value={this.state.idNumber}
                                                onChangeText={(text) => this.setState({idNumber: text})}
                                                placeholder={i18n.t('i247')}
                                            />
                                        </View>
                                    </View>
                                </View>
                            </View>
                            <View style={[base.bg_white, base.content_container, { marginBottom: 20 }]}>
                                <View style={[base.flex_row_start, { paddingVertical: 20 }]}>
                                    <Text style={{fontSize: 18}}>{ i18n.t('photo') }</Text>
                                </View>
                                <View style={[base.flex_row_between, { height: 120 }]}>
                                    <View style={[base.flex_1, base.bg_gray, { marginRight: 30, borderRadius: 10 }]}>
                                        { this.state.idFrontPreview ? (
                                            <Image resizeMode={'contain'} style={{ width: '100%', height: '100%' }} source={this.state.idFrontPreview}/>
                                        ) : (
                                            <Image resizeMode={'contain'} style={{ width: '100%', height: '100%' }} source={require('@images/mine/bg_upload.png')}/>
                                        )}
                                    </View>
                                    <View style={[base.flex_col_center, { alignItems: 'flex-end', width: '20%', height: '100%' }]}>
                                        <View style={[base.flex_col_center, {paddingVertical: 20, width: '100%'}]}>
                                            <Text style={[base.color_gray, { fontSize: 18 }]}>{ i18n.t('front') }</Text>
                                        </View>
                                        <TouchableOpacity onPress={() => this.selectImage(1)} style={[base.flex_row_center, {borderWidth: 1, width: '100%', borderColor: '#ff7606', borderRadius: 3, paddingVertical: 3}]}>
                                            <Text style={[base.color_orange]}>{ i18n.t('sele') }</Text>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                                <View style={[base.flex_row_between, { height: 120, marginTop: 20 }]}>
                                    <View style={[base.flex_1, base.bg_gray, { marginRight: 30, borderRadius: 10 }]}>
                                        { this.state.idBackPreview ? (
                                            <Image resizeMode={'contain'} style={{ width: '100%', height: '100%' }} source={this.state.idBackPreview}/>
                                        ) : (
                                            <Image resizeMode={'contain'} style={{ width: '100%', height: '100%' }} source={require('@images/mine/bg_upload.png')}/>
                                        )}
                                    </View>
                                    <View style={[base.flex_col_center, { alignItems: 'flex-end', width: '20%', height: '100%' }]}>
                                        <View style={[base.flex_col_center, {paddingVertical: 20, width: '100%'}]}>
                                            <Text style={[base.color_gray, { fontSize: 18 }]}>{ i18n.t('back2') }</Text>
                                        </View>
                                        <TouchableOpacity onPress={() => this.selectImage(2)} style={[base.flex_row_center, {borderWidth: 1, width: '100%', borderColor: '#ff7606', borderRadius: 3, paddingVertical: 3}]}>
                                            <Text style={[base.color_orange]}>{ i18n.t('sele') }</Text>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                                <View style={[base.flex_col_center, { height: 150}]}>
                                    <TouchableOpacity onPress={this.submitIdKyc} style={{width: '100%'}}>
                                        <LinearGradient
                                            start={{x: 0, y: 0}}
                                            end={{x: 1, y: 1}}
                                            colors={['#feac1c', '#ff7506']}
                                            style={{ width: '100%', height: 46, borderRadius: 23, justifyContent: 'center', alignItems: 'center' }}
                                        >
                                            <Text style={{color: '#fff', fontSize: 16}}>{ i18n.t('submit') }</Text>
                                        </LinearGradient>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                    ) : (
                        <View style={[{backgroundColor: '#fff', paddingBottom: 30}]}>
                            <View style={[base.bg_white, base.content_container]}>
                                <View style={{paddingBottom: 5}}>
                                    <View style={[base.flex_row_start, { paddingVertical: 5 }]}>
                                        <Image style={{width: 15, height: 15, marginRight: 10}} resizeMode={'contain'} source={require('@images/mine/icon_real_name.png')}/>
                                        <View><Text style={[base.color_orange, { fontSize: 16 }]}>{i18n.t('rname')}</Text></View>
                                    </View>
                                    <View>
                                        <View style={[base.flex_row_between, { marginVertical: 5, height: 45, width: '100%', borderRadius: 5, borderWidth: 0.5, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>
                                            <TextInput
                                                style={[base.color_gray]}
                                                value={this.state.passportName}
                                                onChangeText={(text) => this.setState({passportName: text})}
                                                placeholder={i18n.t('i242')}
                                            />
                                        </View>
                                    </View>
                                </View>
                                <View style={{paddingBottom: 5}}>
                                    <View style={[base.flex_row_start, { paddingVertical: 5 }]}>
                                        <Image style={{width: 15, height: 15, marginRight: 10}} resizeMode={'contain'} source={require('@images/mine/icon_real_name.png')}/>
                                        <View><Text style={[base.color_orange, { fontSize: 16 }]}>{i18n.t('i243')}</Text></View>
                                    </View>
                                    <View>
                                        <View style={[base.flex_row_between, { marginVertical: 5, height: 45, width: '100%', borderRadius: 5, borderWidth: 0.5, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>
                                            <TextInput
                                                style={[base.color_gray]}
                                                value={this.state.passportNumber}
                                                onChangeText={(text) => this.setState({passportNumber: text})}
                                                placeholder={i18n.t('i244')}
                                            />
                                        </View>
                                    </View>
                                </View>
                            </View>
                            <View style={[base.bg_white, base.content_container, { marginBottom: 20 }]}>
                                <View style={[base.flex_row_start, { paddingVertical: 20 }]}>
                                    <Text style={{fontSize: 18}}>{i18n.t('i245')}</Text>
                                </View>
                                <View style={[base.flex_row_between, { height: 120 }]}>
                                    <View style={[base.flex_1, base.bg_gray, { marginRight: 30, borderRadius: 10 }]}>
                                        { this.state.passPortPreview ? (
                                            <Image resizeMode={'contain'} style={{ width: '100%', height: '100%' }} source={this.state.passPortPreview}/>
                                        ) : (
                                            <Image resizeMode={'contain'} style={{ width: '100%', height: '100%' }} source={require('@images/mine/bg_upload.png')}/>
                                        )}
                                    </View>
                                    <View style={[base.flex_col_center, { alignItems: 'flex-end', width: '20%', height: '100%' }]}>
                                        <View style={[base.flex_col_center, {paddingVertical: 20, width: '100%'}]}>
                                            <Text style={[base.color_gray, { fontSize: 18 }]}>{i18n.t('i243')}</Text>
                                        </View>
                                        <TouchableOpacity onPress={() => this.selectImage(3)} style={[base.flex_row_center, {borderWidth: 1, width: '100%', borderColor: '#ff7606', borderRadius: 3, paddingVertical: 3}]}>
                                            <Text style={[base.color_orange]}>{i18n.t('i246')}</Text>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                                <View style={[base.flex_col_center, { height: 150}]}>
                                    <TouchableOpacity onPress={this.submitPassportKyc} style={{width: '100%'}}>
                                        <LinearGradient
                                            start={{x: 0, y: 0}}
                                            end={{x: 1, y: 1}}
                                            colors={['#feac1c', '#ff7506']}
                                            style={{ width: '100%', height: 46, borderRadius: 23, justifyContent: 'center', alignItems: 'center' }}
                                        >
                                            <Text style={{color: '#fff', fontSize: 16}}>{i18n.t('submit')}</Text>
                                        </LinearGradient>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                    ) }
                </ScrollView>
            </View>
        )
    }
}

const styles = StyleSheet.create({
});
